<?php

/**
 * 用户控制器
 */

namespace App\Http\ManagerApi\Controllers;

use App\Api\BaseClass\Controller;
use App\Http\ManagerApi\Models\User;
use Illuminate\Support\Facades\Crypt;
use App\Http\ManagerApi\Models\UserToken;
use Illuminate\Support\Facades\DB;
use App\Http\ManagerApi\Classes\CommissionCalculate;
use App\Http\ManagerApi\Models\TeamMember;
use App\Http\ManagerApi\Models\SystemUser;
use App\Http\ManagerApi\Models\PlatformSetting;
use App\Http\ManagerApi\Models\UserIntegralLog;
use Carbon\Carbon;
use App\Core\Facades\User as UserFacade;
use App\Http\ManagerApi\Models\PlatformRangeSetting;

class PlatformUserController extends Controller
{
    /**
     * 用户列表
     */
    public function listUser()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['level', 'string'],
            ['is_active', 'min:0|max:1'],
            ['is_send', 'min:0|max:1'],
            ['admin_active', 'min:0|max:1'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
            ['my_recommend_code', 'string'],
        ];

        $search = [
            ['where', 'user_name', 'like', '$user_name'],
            ['where', 'mobile', 'like', '$mobile'],
            // ['where', 'id_card_no', 'like', '$id_card_no'],
            ['where', 'is_active', '$is_active'],
            ['where', 'is_send', '$is_send'],
            ['where', 'province', 'like', '$province'],
            ['where', 'city', 'like', '$city'],
            ['where', 'district', 'like', '$district'],
            ['with', 'referee'],
            ['where', 'my_recommend_code', 'like', '$my_recommend_code'],
            ['orderBy', 'id', 'desc'],
        ];

        $format = [
            'user_name' => '%$user_name%',
            'mobile' => '%$mobile%',
            // 'id_card_no' => '%$id_card_no%',
            'province' => '%$province%',
            'city' => '%$city%',
            'district' => '%$district%',
            'my_recommend_code' => '%$my_recommend_code%',
        ];

        $params = $this->form->camelFormOrFail($rules);

        if (isset($params['admin_active']) && $params['admin_active'] === 0) {
            $search[] = ['where', 'operator_id', 0];
        } elseif (isset($params['admin_active']) && $params['admin_active'] === 1) {
            $search[] = ['where', 'operator_id', '>', 0];
        }

        if (isset($params['level']) && !empty($params['level']) && $params['level'] != '创客') {

            $level = PlatformRangeSetting::where('level', $params['level'])->firstOrFail();
            $next_level = PlatformRangeSetting::where('condition', '>', $level->condition)->orderBy('condition')->first();
            if (!isset($next_level)) {
                $search[] = ['where', 'total_achievement', '>=', $level->condition * 10000];
            } else {
                $search[] = ['whereBetween', 'total_achievement', [$level->condition * 10000, $next_level->condition * 10000]];
            }
        } elseif (isset($params['level']) && $params['level'] == '创客') {
            $min_level = PlatformRangeSetting::orderBy('condition')->firstOrFail();
            $search[] = ['where', 'total_achievement', '<', $min_level->condition * 10000];
        }

        $datas = with(new User)->pagination($params, $search, $format);
        foreach ($datas['rows'] as $key => $val) {

            $level = PlatformRangeSetting::where('condition', '<=', $val->total_achievement / 10000)
                ->orderBy('condition', 'desc')
                ->first();
            $val->level = isset($level) ? $level->level : '创客';
        }

        return $this->form->getMessage($datas);
    }

    /**
     * 每日新增用户列表
     */
    public function dayNewUser()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['level', 'string'],
            ['is_active', 'min:0|max:1'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
            ['my_recommend_code', 'string'],
        ];

        $search = [
            ['whereDate', 'updated_at', date('Y-m-d')],
            ['where', 'user_name', 'like', '$user_name'],
            ['where', 'mobile', 'like', '$mobile'],
            // ['where', 'id_card_no', 'like', '$id_card_no'],
            ['where', 'is_active', '$is_active'],
            ['where', 'province', 'like', '$province'],
            ['where', 'city', 'like', '$city'],
            ['where', 'district', 'like', '$district'],
            ['orderBy', 'created_at', 'desc']
        ];

        $format = [
            'user_name' => '%$user_name%',
            'mobile' => '%$mobile%',
            // 'id_card_no' => '%$id_card_no%',
            'province' => '%$province%',
            'city' => '%$city%',
            'district' => '%$district%',
            'my_recommend_code' => '%$my_recommend_code%',
        ];

        $params = $this->form->camelFormOrFail($rules);

        if (isset($params['level']) && !empty($params['level']) && $params['level'] != '创客') {

            $level = PlatformRangeSetting::where('level', $params['level'])->firstOrFail();
            $next_level = PlatformRangeSetting::where('condition', '>', $level->condition)->orderBy('condition')->first();
            if (!isset($next_level)) {
                $search[] = ['where', 'total_achievement', '>=', $level->condition * 10000];
            } else {
                $search[] = ['whereBetween', 'total_achievement', [$level->condition * 10000, $next_level->condition * 10000]];
            }
        } elseif (isset($params['level']) && $params['level'] == '创客') {
            $min_level = PlatformRangeSetting::orderBy('condition')->firstOrFail();
            $search[] = ['where', 'total_achievement', '<', $min_level->condition * 10000];
        }

        $datas = with(new User)->pagination($params, $search, $format);
        foreach ($datas['rows'] as $val) {

            $level = PlatformRangeSetting::where('condition', '<=', $val->total_achievement)
                ->orderBy('condition', 'desc')
                ->first();
            $val->level = isset($level) ? $level->level : '创客';
            if (isset($params['level']) && $val->level != $params['level']) {
                unset($datas['rows'][$key]);
            }
        }

        array_values($datas['rows']->toArray());

        return $this->form->getMessage($datas);
    }

    /**
     * 每周新增用户列表
     */
    public function weekNewUser()
    {
        $current_weekday = date('N');
        $start = Carbon::today()->subDays($current_weekday);
        $end = Carbon::tomorrow();

        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['level', 'string'],
            ['is_active', 'min:0|max:1'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
            ['my_recommend_code', 'string'],
        ];

        $search = [
            ['where', 'updated_at', '>', $start],
            ['where', 'updated_at', '<', $end],
            ['where', 'user_name', 'like', '$user_name'],
            ['where', 'mobile', 'like', '$mobile'],
            // ['where', 'id_card_no', 'like', '$id_card_no'],
            ['where', 'is_active', '$is_active'],
            ['where', 'province', 'like', '$province'],
            ['where', 'city', 'like', '$city'],
            ['where', 'district', 'like', '$district'],
            ['orderBy', 'created_at', 'desc']
        ];

        $format = [
            'user_name' => '%$user_name%',
            'mobile' => '%$mobile%',
            // 'id_card_no' => '%$id_card_no%',
            'province' => '%$province%',
            'city' => '%$city%',
            'district' => '%$district%',
            'my_recommend_code' => '%$my_recommend_code%',
        ];

        $params = $this->form->camelFormOrFail($rules);

        if (isset($params['level']) && !empty($params['level']) && $params['level'] != '创客') {

            $level = PlatformRangeSetting::where('level', $params['level'])->firstOrFail();
            $next_level = PlatformRangeSetting::where('condition', '>', $level->condition)->orderBy('condition')->first();
            if (!isset($next_level)) {
                $search[] = ['where', 'total_achievement', '>=', $level->condition * 10000];
            } else {
                $search[] = ['whereBetween', 'total_achievement', [$level->condition * 10000, $next_level->condition * 10000]];
            }
        } elseif (isset($params['level']) && $params['level'] == '创客') {
            $min_level = PlatformRangeSetting::orderBy('condition')->firstOrFail();
            $search[] = ['where', 'total_achievement', '<', $min_level->condition * 10000];
        }

        $datas = with(new User)->pagination($params, $search, $format);
        foreach ($datas['rows'] as $val) {

            $level = PlatformRangeSetting::where('condition', '<=', $val->total_achievement)
                ->orderBy('condition', 'desc')
                ->first();
            $val->level = isset($level) ? $level->level : '创客';
            if (isset($params['level']) && $val->level != $params['level']) {
                unset($datas['rows'][$key]);
            }
        }

        array_values($datas['rows']->toArray());

        return $this->form->getMessage($datas);
    }

    /**
     * 每月新增用户列表
     */
    public function monthNewUser()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['level', 'string'],
            ['is_active', 'min:0|max:1'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
            ['my_recommend_code', 'string'],
        ];

        $search = [
            ['whereYear', 'updated_at', date('Y')],
            ['whereMonth', 'updated_at', date('m')],
            ['where', 'user_name', 'like', '$user_name'],
            ['where', 'mobile', 'like', '$mobile'],
            // ['where', 'id_card_no', 'like', '$id_card_no'],
            ['where', 'is_active', '$is_active'],
            ['where', 'province', 'like', '$province'],
            ['where', 'city', 'like', '$city'],
            ['where', 'district', 'like', '$district'],
            ['orderBy', 'created_at', 'desc']
        ];

        $format = [
            'user_name' => '%$user_name%',
            'mobile' => '%$mobile%',
            // 'id_card_no' => '%$id_card_no%',
            'province' => '%$province%',
            'city' => '%$city%',
            'district' => '%$district%',
            'my_recommend_code' => '%$my_recommend_code%',
        ];

        $params = $this->form->camelFormOrFail($rules);

        if (isset($params['level']) && !empty($params['level']) && $params['level'] != '创客') {

            $level = PlatformRangeSetting::where('level', $params['level'])->firstOrFail();
            $next_level = PlatformRangeSetting::where('condition', '>', $level->condition)->orderBy('condition')->first();
            if (!isset($next_level)) {
                $search[] = ['where', 'total_achievement', '>=', $level->condition * 10000];
            } else {
                $search[] = ['whereBetween', 'total_achievement', [$level->condition * 10000, $next_level->condition * 10000]];
            }
        } elseif (isset($params['level']) && $params['level'] == '创客') {
            $min_level = PlatformRangeSetting::orderBy('condition')->firstOrFail();
            $search[] = ['where', 'total_achievement', '<', $min_level->condition * 10000];
        }

        $datas = with(new User)->pagination($params, $search, $format);
        foreach ($datas['rows'] as $val) {

            $level = PlatformRangeSetting::where('condition', '<=', $val->total_achievement)
                ->orderBy('condition', 'desc')
                ->first();
            $val->level = isset($level) ? $level->level : '创客';
            if (isset($params['level']) && $val->level != $params['level']) {
                unset($datas['rows'][$key]);
            }
        }

        array_values($datas['rows']->toArray());

        return $this->form->getMessage($datas);
    }

    /**
     * 用户详情
     */
    public function userDetail()
    {
        $rules = [['id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        return $this->form->getMessage(User::find($params['id']));
    }

    /**
     * 更新信息
     */
    public function updateUser()
    {
        $rules = [
            ['id', 'required|integer'],
            ['user_name', 'string'],
            ['nick_name', 'string'],
            ['mobile', 'string'],
            ['id_card_no', 'string'],
            ['password', 'string|between:4,12'],
            ['card_no', 'string'],
            ['address', 'string'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        // 修改密码
        if (isset($params['password']) && !empty($params['password'])) {
            $params['password'] = Crypt::encryptString($params['password']);
        }

        $user = User::findOrFail($params['id']);
        // 修改昵称
        if (isset($params['nick_name']) && $user->nick_name != $params['nick_name'] && User::where('nick_name', $params['nick_name'])->exists()) {
            return $this->form->error('该昵称已被使用');
        }

        return $this->form->updateMessage($user->fill($params)->save());
    }

    /**
     * 删除用户
     */
    public function deleteUser()
    {
        $rules = [['id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);
        if ($user->is_active == 1) {
            return $this->form->error('已激活用户不能删除！');
        }

        try {
            UserToken::where('uid', $user->id)->delete();
            $user->delete();
        } catch (\Exception $e) {
            return $this->form->error('删除失败，请重试');
        }

        return $this->form->success('删除成功');
    }

    /**
     * 用户树
     */
    public function userTree()
    {
        $params['id'] = User::where('recommend_code', '10000')->firstOrFail()->id;

        $parent = [
            'manager' => [],
            'managerChildren' => []
        ];
        $user = User::select('id', 'user_name')->findOrFail($params['id']);
        $parent['manager'] = ['id' => $user->id, 'userName' => $user->user_name];
        $parent['managerChildren'] = $this->getUserTree($params['id']);

        return $this->form->datas($parent);
    }

    /**
     * 返回用户树
     */
    public function getUserTree($uid)
    {
        $childNodes = [];
        $sub_users = TeamMember::where('uid', $uid)->get()->toArray();
        $users = User::whereIn('id', array_column($sub_users, 'sub_uid'))->get()->toArray();
        foreach ($users as $user) {
            $childNodes[] = [
                'manager' => ['id' => $user['id'], 'userName' => $user['user_name']],
                'managerChildren' => $this->getUserTree($user['id'])
            ];
        }
        return $childNodes;
    }

    /**
     * 金豆充值
     */
    public function integralRecharge()
    {
        $rules = [
            ['recommend_code', 'required'],
            ['changed_integral', 'required|integer'],
            ['password', 'required'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        if ($params['changed_integral'] <= 0) {
            return $this->form->error('充值金豆数错误');
        }

        $setting = PlatformSetting::firstOrFail();
        if ($params['password'] != Crypt::decryptString($setting->activation_cipher)) {
            return $this->form->error('密码错误');
        }

        DB::transaction(function () use ($params) {

            $user = User::where('my_recommend_code', $params['recommend_code'])->firstOrFail();
            $user->increment('integral', $params['changed_integral']);

            // 插入积分记录表
            $create = [
                'uid' => $user->id,
                'changed_integral' => $params['changed_integral'],
                'current_integral' => $user->integral,
                'flag' => 1,
                'type' => 8,
                'is_finished' => 1,
                'desc' => "金豆充值"
            ];
            UserIntegralLog::create($create);
        });

        return $this->form->success('充值成功');
    }

    /**
     * 指定用户直属下级
     */
    public function userSub()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['id', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['id_card_no', 'string'],
            ['is_active', 'min:0|max:1'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $sql = DB::table('team_member as tm')
            ->join('user as u', 'u.id', '=', 'tm.sub_uid')
            ->where('tm.uid', $params['id']);

        if (isset($params['user_name']) && !empty($params['user_name'])) {
            $sql = $sql->where('u.user_name', 'like', "%{$params['user_name']}%");
        }

        if (isset($params['mobile']) && !empty($params['mobile'])) {
            $sql = $sql->where('u.mobile', 'like', "%{$params['mobile']}%");
        }

        if (isset($params['id_card_no']) && !empty($params['id_card_no'])) {
            $sql = $sql->where('u.id_card_no', 'like', "%{$params['id_card_no']}%");
        }

        if (isset($params['is_active'])) {
            $sql = $sql->where('u.is_active', $params['is_active']);
        }

        if (isset($params['province']) && !empty($params['province'])) {
            $sql = $sql->where('u.province', 'like', "%{$params['province']}%");
        }

        if (isset($params['city']) && !empty($params['city'])) {
            $sql = $sql->where('u.city', 'like', "%{$params['city']}%");
        }

        if (isset($params['district']) && !empty($params['district'])) {
            $sql = $sql->where('u.district', 'like', "%{$params['district']}%");
        }

        $return = ['total' => 0, 'rows' => []];

        $return['total'] = $sql->count();
        if ($return['total'] > 0) {
            $return['rows'] = $sql->select('u.*')->skip($params['offset'])->take($params['limit'])->orderBy('id', 'desc')->get();
        }

        return $this->form->getMessage($return);
    }

    /**
     *用户激活
     */
    public function activeUser()
    {
        $rules = [
            ['id', 'required|integer|min:1'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);
        if ($user->is_active != 0) {
            return $this->form->error('已激活，请勿重复操作');
        }

        DB::transaction(function () use ($user) {

            // 激活
            $user->update(['is_active' => 1, 'operator_id' => UserFacade::user()->id]);


            // 加入团队表
            $sup_id = User::where('is_active', 1)->where('my_recommend_code', $user->recommend_code)->firstOrFail()->id;

            TeamMember::create(['uid' => $sup_id, 'sub_uid' => $user->id]);
        });

        return $this->form->success('激活成功');
    }

    /**
     * 激活密码验证
     */
    public function passwordVerify()
    {
        $rules = [['password', 'required']];

        $params = $this->form->camelFormOrFail($rules);

        $setting = PlatformSetting::firstOrFail();
        if ($params['password'] != Crypt::decryptString($setting->activation_cipher)) {
            return $this->form->error('密码错误');
        }

        return $this->form->success();
    }

    /**
     * 发货
     */
    public function send()
    {
        $rules = [['id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);

        if ($user->is_active == 0) {
            return $this->api->error('账号未激活，发货失败');
        }

        if ($user->is_send != 0) {
            return $this->api->error('已发货，请勿重复操作');
        }

        return $this->form->updateMessage($user->update(['is_send' => 1]));
    }

    /**
     * 设置股东(运营中心)
     */
    public function setPartner()
    {
        $rules = [
            ['id', 'required|integer'],
            ['is_partner', 'required|integer'],
            ['password', 'required|string'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);

        if ($user->is_active == 0) {
            return $this->form->error('该用户暂未激活！');
        }

        $set = PlatformSetting::firstOrFail();
        if (Crypt::decryptString($set->activation_cipher) != $params['password']) {
            return $this->form->error('验证密码错误！');
        }

        if ($user->is_shareholder == 1) {
            return $this->form->error('您已经是股东了，不能设置为运营中心');
        }

        unset($params['password']);
        $params['partner_time'] = $params['is_partner'] ? time() : null;

        return $this->form->updateMessage($user->fill($params)->save());
    }

    /**
     * 设置股东
     */
    public function setShareholder()
    {
        $rules = [
            ['id', 'required|integer'],
            ['is_shareholder', 'required|integer'],
            ['password', 'required|string'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);

        if ($user->is_active == 0) {
            return $this->form->error('该用户暂未激活！');
        }

        $set = PlatformSetting::firstOrFail();
        if (Crypt::decryptString($set->activation_cipher) != $params['password']) {
            return $this->form->error('验证密码错误！');
        }

        if ($user->is_partner == 1) {
            return $this->form->error('您已经是运营中心了，不能设置为股东');
        }

        unset($params['password']);

        return $this->form->updateMessage($user->fill($params)->save());
    }
}